// uploadRouter.js
const express = require('express');
const router = express.Router();
const multer = require('multer');
const fs = require('fs');
const path = require('path');

// 定义一个创建存储配置的函数
function createStorage(dirName) {
  const storageDir = path.join(__dirname, '../public', dirName);
  
  // 如果目录不存在就创建
  if (!fs.existsSync(storageDir)) {
    fs.mkdirSync(storageDir, { recursive: true });
  }

  return multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, storageDir); 
    },
    filename: (req, file, cb) => {
      const ext = path.extname(file.originalname);
      const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
      cb(null, `image-${uniqueSuffix}${ext}`); 
    }
  });
}

// 使用不同的存储配置
const uploadPost = multer({ storage: createStorage('postsImages') });
const uploadCharacter = multer({ storage: createStorage('charactersImages') });

const protocol = 'http';
const host = 'localhost:3000';

router.post('/post_image', uploadPost.single('file'), (req, res) => {
  try {
    const imageUrl = `${protocol}://${host}/postsImages/${req.file.filename}`;
    res.json({ url: imageUrl });
  } catch (err) {
    res.status(500).json({ error: '图片上传失败' });
  }
});

router.post('/character_image', uploadCharacter.single('file'), (req, res) => {
  try {
    const imageUrl = `${protocol}://${host}/charactersImages/${req.file.filename}`;
    res.json({ url: imageUrl });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '图片上传失败' });
  }
});
module.exports = router;